package com.test.webscoket.main;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RedisMessageListener implements MessageListener {

    @Autowired
    private WebSocketSessionManager webSocketSessionManager;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(pattern);
        String clientId = channel.substring("websocket-messages:".length());
        String messageBody = new String(message.getBody());
        try {
            if (messageBody.startsWith("unRegister")){
                webSocketSessionManager.removeSession(clientId);
            } else if (messageBody.startsWith("message")){
                webSocketSessionManager.sendMessageToClient(clientId, messageBody);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
